package com.dailyblue.servlet.ajax.controller;

import com.alibaba.fastjson.JSONArray;
import com.dailyblue.java.jdbc.pack0325.bean.Emp;
import com.dailyblue.java.jdbc.pack0325.dao.EmpDAO;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@WebServlet("/emp")
public class EmpController extends ReflectionController {
    private EmpDAO edao = new EmpDAO();

    public void find(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 1⃣️ 调用DAO包的查询方法获取到数据
        List<Emp> list = edao.findAllEmp();
        // 2⃣️ 将返回的数据格式转换成JSON格式的
        String json = JSONArray.toJSONString(list);
        // 3⃣️ 把JSON字符串返回给浏览器
        response.setContentType("application/json;charset=utf-8");
        PrintWriter out = response.getWriter();
        out.println(json);
    }

    public void page(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 1⃣️ 获取用户传递的页码
        int page = 1; // 默认页码
        String p = request.getParameter("page");
        if (p != null) {
            page = Integer.parseInt(p);
        }
        // 2⃣️ 调用DAO包类获取数据
        List<Emp> list = edao.findEmp(page);
        // 3⃣️ 转换成JSON字符串
        String json = JSONArray.toJSONString(list);
        // 4⃣️ 响应数据
        response.setContentType("application/json;charset=utf-8");
        PrintWriter out = response.getWriter();
        out.println(json);
    }

    public void pageNum(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        int pages = edao.getAllPageNum(5);
        PrintWriter out = response.getWriter();
        out.println(pages);
    }

    public void delete(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //System.out.println("用户执行了delete方法");
        int id = Integer.parseInt(request.getParameter("id"));
        //System.out.println("id:" + id);
        edao.deleteEmp(id);
        PrintWriter out = response.getWriter();
        out.println(1);

    }
}
